﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Core;
using Tesla.Graphics;
using Tesla.Graphics.Implementation;
using XFG = Microsoft.Xna.Framework.Graphics;

namespace Tesla.Xna.Graphics.Implementation {
    /// <summary>
    /// Concrete XNA 4.0 implementation for <see cref="IndexBuffer"/>.
    /// </summary>
    public sealed class XNAIndexBufferImplementation : IndexBufferImplementation {
        private XNARenderer _renderer;
        private XFG.GraphicsDevice _graphicsDevice;
        private XFG.IndexBuffer _indexBuffer;

        /// <summary>
        /// Gets the XNA renderer that created this object.
        /// </summary>
        internal XNARenderer Renderer {
            get {
                return _renderer;
            }
        }

        /// <summary>
        /// Gets the actual XNA IndexBuffer object.
        /// </summary>
        internal XFG.IndexBuffer XNAIndexBuffer {
            get {
                return _indexBuffer;
            }
        }

        /// <summary>
        /// Gets the XNA index format enumeration equivalent.
        /// </summary>
        internal XFG.IndexElementSize XNAIndexFormat {
            get {
                return (base.IndexFormat == IndexFormat.ThirtyTwoBits) ? XFG.IndexElementSize.ThirtyTwoBits : XFG.IndexElementSize.SixteenBits;
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="XNAIndexBufferImplementation"/>.
        /// </summary>
        /// <param name="renderer">The XNA renderer.</param>
        /// <param name="format">The index format.</param>
        /// <param name="indexCount">The number of indices.</param>
        /// <param name="usage">The buffer usage specifying what type of memory the buffer should be created in.</param>
        internal XNAIndexBufferImplementation(XNARenderer renderer, IndexFormat format, int indexCount, ResourceUsage usage)
            : base(format, indexCount, usage) {
                _renderer = renderer;
                _graphicsDevice = renderer.GraphicsDevice;

                if(usage == ResourceUsage.Static) {
                    _indexBuffer = new XFG.IndexBuffer(_graphicsDevice, XNAIndexFormat, indexCount, XFG.BufferUsage.None);
                } else {
                    _indexBuffer = new XFG.DynamicIndexBuffer(_graphicsDevice, XNAIndexFormat, indexCount, XFG.BufferUsage.None);
                }
        }

        /// <summary>
        /// Creates a new instance of <see cref="XNAIndexBufferImplementation"/>.
        /// </summary>
        /// <param name="renderer">The XNA renderer.</param>
        /// <param name="indices">The index data</param>
        /// <param name="usage">The buffer usage specifying what type of memory the buffer should be created in.</param>
        internal XNAIndexBufferImplementation(XNARenderer renderer, DataBuffer<int> indices, ResourceUsage usage) 
            : base(indices, usage) {

                _renderer = renderer;
                _graphicsDevice = renderer.GraphicsDevice;

                if(usage == ResourceUsage.Static) {
                    _indexBuffer = new XFG.IndexBuffer(_graphicsDevice, XNAIndexFormat, indices.Length, XFG.BufferUsage.None);
                } else {
                    _indexBuffer = new XFG.DynamicIndexBuffer(_graphicsDevice, XNAIndexFormat, indices.Length, XFG.BufferUsage.None);
                }
                _indexBuffer.SetData<int>(indices.Buffer);
        }

        /// <summary>
        /// Creates a new instance of <see cref="XNAIndexBufferImplementation"/>.
        /// </summary>
        /// <param name="renderer">The XNA renderer.</param>
        /// <param name="indices">The index data</param>
        /// <param name="usage">The buffer usage specifying what type of memory the buffer should be created in.</param>
        internal XNAIndexBufferImplementation(XNARenderer renderer, DataBuffer<short> indices, ResourceUsage usage)
            : base(indices, usage) {
            if(indices == null) {
                throw new ArgumentNullException("indices", "Indices cannot be null.");
            }

            _renderer = renderer;
            _graphicsDevice = renderer.GraphicsDevice;

            if(usage == ResourceUsage.Static) {
                _indexBuffer = new XFG.IndexBuffer(_graphicsDevice, XNAIndexFormat, indices.Length, XFG.BufferUsage.None);
            } else {
                _indexBuffer = new XFG.DynamicIndexBuffer(_graphicsDevice, XNAIndexFormat, indices.Length, XFG.BufferUsage.None);
            }

            _indexBuffer.SetData<short>(indices.Buffer);
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="XNAIndexBufferImplementation"/> is reclaimed by garbage collection.
        /// </summary>
        ~XNAIndexBufferImplementation() {
            Dispose(false);
        }

        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <param name="startIndex">Starting index in the array at which to start copying from</param>
        /// <param name="elementCount">Number of indices to write</param>
        /// <param name="offsetInBytes">Offset from the start of the index buffer at which to start writing at</param>
        /// <param name="writeOptions">Write options, used only if this is a dynamic buffer. None, discard, no overwrite</param>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public override void SetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, DataWriteOptions writeOptions) {
            if(base.BufferUsage == ResourceUsage.Static) {
                _indexBuffer.SetData<T>(offsetInBytes, data, startIndex, elementCount);
            } else {
                if(writeOptions == DataWriteOptions.None) {
                    ((XFG.DynamicIndexBuffer) _indexBuffer).SetData<T>(offsetInBytes, data, startIndex, elementCount, XFG.SetDataOptions.None);
                } else {
                    XFG.SetDataOptions mode = (writeOptions == DataWriteOptions.Discard) ? XFG.SetDataOptions.Discard : XFG.SetDataOptions.NoOverwrite;
                    ((XFG.DynamicIndexBuffer) _indexBuffer).SetData<T>(offsetInBytes, data, startIndex, elementCount, mode);
                }
            }
        }

        /// <summary>
        /// Reads data from the index buffer into the array.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to write the data to</param>
        /// <param name="startIndex">Starting index in the array at which to start writing to</param>
        /// <param name="elementCount">Number of indices to read</param>
        /// <param name="offsetInBytes">Offset from the start of the index buffer at which to start copying from/param>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public override void GetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes) {
            _indexBuffer.GetData<T>(offsetInBytes, data, startIndex, elementCount);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing) {
            if(!IsDisposed) {
                //Dispose of managed resources
                if(disposing) {
                    if(_indexBuffer != null) {
                        _indexBuffer.Dispose();
                    }
                }
            }
            base.Dispose(disposing);
        }
    }
}
